// 配置参数
const config = {
    timeout: 5000, // 检测超时时间
    retryCount: 2, // 失败重试次数
    goodThreshold: 800, // 良好阈值(ms)
    mediumThreshold: 1500 // 中等阈值(ms)
};

// 延迟检测器（改用GET请求并添加防缓存头）
async function checkLatency(url) {
    let bestLatency = Infinity;

    for (let i = 0; i < config.retryCount; i++) {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), config.timeout);

        try {
            const startTime = performance.now();
            await fetch(url, {
                method: 'GET', // 改为GET方法
                mode: 'no-cors',
                cache: 'no-cache',
                headers: { // 添加防缓存头
                    'Cache-Control': 'no-cache',
                    'Pragma': 'no-cache'
                },
                signal: controller.signal
            });
            const latency = performance.now() - startTime;
            if (latency < bestLatency) bestLatency = latency;
        } catch (error) {
            // 忽略错误继续重试
        } finally {
            clearTimeout(timeoutId);
        }
    }

    return bestLatency !== Infinity ? Math.round(bestLatency) : null;
}

// 更新状态显示
function updateStatus() {
    const statusElement = document.getElementById('liveStatus');
    const date = new Date();
    statusElement.textContent = `实时检测正常 ${date.toLocaleTimeString()}`;
}

// 初始化检测（添加错误处理）
async function initDetection() {
    const latencyElements = document.querySelectorAll('.latency');

    latencyElements.forEach(element => {
        element.classList.add('loading');
        element.innerHTML = '<span class="loading-text">检测中...</span>';
    });

    try {
        const promises = Array.from(latencyElements).map(async element => {
            try {
                const url = element.dataset.url;
                const latency = await checkLatency(url);
                return { element, latency };
            } catch (error) {
                return { element, latency: null };
            }
        });

        const results = await Promise.all(promises);

        results.forEach(({ element, latency }) => {
            element.classList.remove('loading');
            if (latency === null) {
                element.textContent = '❌ 无法访问';
                element.classList.add('bad');
            } else {
                element.textContent = `${latency}ms`;
                element.classList.remove('bad', 'medium', 'good');
                if (latency < config.goodThreshold) {
                    element.classList.add('good');
                } else if (latency < config.mediumThreshold) {
                    element.classList.add('medium');
                } else {
                    element.classList.add('bad');
                }
            }
        });

        updateStatus();
    } catch (error) {
        console.error('检测过程中发生错误:', error);
    }
}

// 其余代码保持不变...


// 跳转处理功能（修复空白标签页问题）
function setupRedirects() {
    const links = document.querySelectorAll('a[target="_blank"]');
    const loader = document.getElementById('loader');
    const loaderText = document.getElementById('loaderText');
    const progressBar = document.getElementById('progressBar');

    links.forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const targetUrl = this.href;

            // 显示加载页面
            loader.classList.add('active');
            loaderText.textContent = `正在跳转到：${new URL(targetUrl).hostname}`;

            // 模拟进度条
            let progress = 0;
            const interval = setInterval(() => {
                progress += 10;
                progressBar.style.width = `${progress}%`;
                if (progress >= 100) {
                    clearInterval(interval);
                    // 实际跳转
                    setTimeout(() => {
                        window.open(targetUrl, '_blank'); // 直接跳转
                        // 隐藏加载页面
                        loader.classList.remove('active');
                        progressBar.style.width = '0';
                    }, 500); // 延迟 500ms 确保动画完成
                }
            }, 30);
        });
    });
}

// 初始化
window.addEventListener('DOMContentLoaded', () => {
    initDetection();
    setupRedirects();
});

// 每5分钟自动刷新
setInterval(initDetection, 5 * 60 * 1000);